
<html>
  <head>
    <title>TF2 Auto Playlist</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
    <script type="text/javascript" src="swfobject.js"></script>    
    <script type="text/javascript">

	  var viewedVideos = [];
        
        jQuery(document).ready(function() {
        	jQuery.ajax({
		    async: false,
                url: "CookieUpdate",
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    viewedVideos = data;
                    
        			for ( var x = 0; x < viewedVideos.length; x++ ) {
            			viewedMap[viewedVideos[x]] = true;
        			}
                },
                complete: function() {
                }
            });
        });
        
        var tag = "TF2AutoPlaylist";
        
        function updateViewed(viewId) {
            viewedMap[viewId] = true;
            jQuery.ajax({
                url: "CookieUpdate?id=" + viewId,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    viewedVideos = data;
                },
                complete: function() {
                }
            });
        }
        
        var totalVideos = 0;
        var videos = [];
        var viewedMap = {};
        var youtubeSrcTemplate = "http://www.youtube.com/e/<id>?enablejsapi=1&playerapiid=ytplayer";

        function addVideos(start, uri) {
            var rand = Math.random();
		if ( uri == null ) {
			uri = "http://gdata.youtube.com/feeds/api/videos/-/" + tag + "?rand=" + rand + "&start-index=" + start + "&v=2&alt=json-in-script&format=6";
		}
            jQuery.ajax({
                url: uri,
                dataType: 'jsonp',
                type: 'GET',
                success: function(data) {
                    var elements = data.feed.entry;
			var total = data.feed['openSearch$totalResults']['$t'];
			var start = data.feed['openSearch$startIndex']['$t'];
			var items = data.feed['openSearch$itemsPerPage']['$t'];

                    if ( elements == null ) {
				var links = data.feed.link;
				var next = null;
				
				for ( var n = 0; n < links.length; n++ ) {
					if ( links[n].rel == 'next' )
						next = links[n].href;
				}
				if ( next != null && start+items < total ) {
	                        addVideos(i+start, next);
					return;
				}
                        renderVideos();
                        getRandomVideoNotViewed();
                        return;
                    }
                    for ( var i = 0; i < elements.length; i++ ) {
                        try {
                        var id = elements[i]['media$group']['yt$videoid']['$t'];
                        var name = elements[i]['media$group']['media$title']['$t'];
                        var creator = elements[i]['author'][0]['name']['$t'];
                        var views = elements[i]['yt$statistics']['viewCount'];
                        videos.push({
                            id: id,
                            name: name,
                            creator: creator,
                            views: views
                        });
                        } catch (e) {

                        }
                    }

                    if ( i < data.feed['openSearch$totalResults']['$t'] ) {
				var links = data.feed.link;
				var next = null;
				for ( var n = 0; n < links.length; n++ ) {
					if ( links[n].rel == 'next' )
						next = links[n].href;
				}
                        addVideos(i+start, next);
                    } else {
                        renderVideos();
                        getRandomVideoNotViewed();
                    }
                }
            });
        }

        
        function renderVideos() {
            jQuery("#mainTable").show();
            document.getElementById('videosFound').innerHTML = videos.length + " videos found.";
            document.getElementById("bleh").innerHTML = "";
            document.getElementById("videoTbody").innerHTML = "";
            allViewed = true;
            for ( var i = 0; i < videos.length; i++ ) {
                var tr = document.createElement("tr");
                var viewsTd = document.createElement("td");
                if ( videos[i].views > 1000 ) {
                    viewsTd.setAttribute("style","color: green");
                } else if ( viewedMap[videos[i].id] ) {
                    viewsTd.setAttribute("style","color: black");
                } else {
                    viewsTd.setAttribute("style","color: red");
                    allViewed = false;
                }
                viewsTd.innerHTML = "<b>" + videos[i].views;
                var nameTd = document.createElement("td");
                nameTd.innerHTML = videos[i].name;
                var creatorTd = document.createElement("td");
                creatorTd.innerHTML = videos[i].creator;
                tr.appendChild(viewsTd);
                tr.appendChild(nameTd);
                tr.appendChild(creatorTd);
                document.getElementById("videoTbody").appendChild(tr);
            }
        }
        
        var playerReady = false;
        var allViewed = false;
        
        function getRandomVideoNotViewed() {
          	clearTimeout(cutoff);
            if ( allViewed ) {
            	if ( videoWindow != null )
            		videoWindow.close();
                document.getElementById("bleh").innerHTML = "<b style='color: green'>All videos have been viewed, refreshing in one minute</b>";
                setTimeout(function() {
                    window.top.location = window.top.location;
                }, 60000);
                return;
            }
            var random = Math.floor(Math.random()*videos.length);
            var selectedVideo = videos[random];
            if ( selectedVideo == null || viewedMap[selectedVideo.id] ){
                getRandomVideoNotViewed();
            } else {
                viewVideo(selectedVideo);
            }
        }
        
        var videoWindow = null;
        var videoWindows = [];
        
        function viewVideo(video) {
            if ( videoWindow != null && videoWindow.top != null ) {
                videoWindow.top.location = "http://www.youtube.com/watch?v=" + video.id;
            } else {
                videoWindow = window.open("http://www.youtube.com/watch?v=" + video.id, "", "height=200,width=200");
            }
            if ( !playerReady ) {
                var params = { allowScriptAccess: "always" };
                var atts = { id: "myytplayer" };
                var url = youtubeSrcTemplate.replace("<id>",video.id);
                try {
                swfobject.embedSWF(url,
                                   "ytapiplayer", "425", "356", "8", null, null, params, atts);
                }catch(e){ }
                updateViewed(video.id);
            } else {
                var player = document.getElementById("myytplayer");
                player.cueVideoById(video.id);
                updateViewed(video.id);
                playVideo();
            }
            renderVideos();
        }
        
          function onYouTubePlayerReady(playerId) {
              playerReady = true;
              playVideo();
          }
          
          
          var cutoff = null;
          
          function cutoffAfter1Minute() {
              getRandomVideoNotViewed();
          }
          
          function seeIfNextVideoIsUp() {
              var player = document.getElementById("myytplayer");
              if ( player.getPlayerState() == 0 ) {
                  getRandomVideoNotViewed();
              } else {
                  setTimeout(function() {
                      seeIfNextVideoIsUp()
                  }, 4000);
              }
          }
          
          
          function playVideo() {
              var player = document.getElementById("myytplayer");
              player.playVideo();
              player.mute();
              setTimeout(function() {
                  seeIfNextVideoIsUp()
              }, 4000);
              clearTimeout(cutoff);
              cutoff = setTimeout(function() {
              	cutoffAfter1Minute();
              }, 50000);
          }
        
    </script>
    <style>
        
        table {
            border: 1px solid black;
            border-bottom: 0px;
            border-right: 0px;
        }
        
        td, th {
            padding: 12px;
            border-bottom: 1px solid black;
            border-right: 1px solid #999999;
        }
    </style>
  </head>

  <body onload="addVideos(1);">
      
      <b>To reset all your views, delete all cookies from this site.</b>
      <br/>
      <p>   To get your video added to this list add the tag <b>TF2AutoPlaylist</b> to your video.
It might take a couple minutes for it to update but it will eventually show up here.  
An example can be seen <a target="_blank" href="http://www.youtube.com/watch?v=8MxmpqDj_Fw">here</a>.</p>
      <pre>
Views Legend:
 Red = You haven't viewed it and it hasn't reached 1000 views
 Black = You have viewed this video
 Green = This video has reached 1000 views
      </pre>
      <p>
          This will randomly select a video from this list and play it if you haven't viewed it before.  
          You will not see any videos that you have seen before or have over 1000 views.  If your video
          reaches over 1000 views please remove the <b>TF2AutoPlaylist</b> tag from your video.  <b>Videos
          be cycled when they complete.</b>
      </p>
      <br/>
      <div id=videosFound></div>
  <center>
      <div id="ytapiplayer">
          
      </div>
  </center>
  <br/>
     
      <div id="bleh">Loading video list...</div>
      
      <table id="mainTable" width="100%" cellspacing="0" cellpadding="0" style="display: none;">
          <thead>
              <tr>
                  <th>Views</th>
                  <th>Name</th>
                  <th>Creator</th>
              </tr>
          </thead>
          <tbody id="videoTbody">
              
          </tbody>
      </table>
      
  </body>
</html>
